package cn.edu.hqu.cst.crj.servicedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btnBind;
    Button btnUnbind;
    Button btnGetServiceStatus;
    TextView tvServiceStatus;

    //保持所启动的Service的IBinder对象
    BindService.MyBinder serviceBinder;
    boolean isServiceBind=false;


    private ServiceConnection conn = new ServiceConnection() {
        //连接成功时
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("~~~~~Connected~~~~~");
            //获取Service的onBind方法返回的MyBinder对象
            serviceBinder = (BindService.MyBinder) service;
           // tvServiceStatus.setText("连接成功");
        }

        //连接失败时
        @Override
        public void onServiceDisconnected(ComponentName name) {
            System.out.println("~~~~~Disconnected~~~~~");
            //tvServiceStatus.setText("连接失败");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取程序界面中的bind、unbind、getServiceStatus按钮
        btnBind = findViewById(R.id.bindService);
        btnUnbind = findViewById(R.id.unBindService);
        btnGetServiceStatus = findViewById(R.id.getService);
        tvServiceStatus= findViewById(R.id.text);

        btnBind.setOnClickListener(this);
        btnUnbind.setOnClickListener(this);
        btnGetServiceStatus.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
        intent.setClass(MainActivity.this,BindService.class);

        switch (v.getId()){
            case R.id.bindService:
                if(!isServiceBind){
                    bindService(intent, conn, BIND_AUTO_CREATE);
                    isServiceBind=true;
                }
                tvServiceStatus.setText("绑定服务");
                break;

            case R.id.unBindService:
                if(isServiceBind){
                    unbindService(conn);
                    isServiceBind=false;
                }
                tvServiceStatus.setText("解绑服务");
                break;
            case R.id.getService:

                String text="Service的count值为：";
                text+= Integer.toString(serviceBinder.getCount());
                tvServiceStatus.setText(text);
                break;

        }

    }

}
